package cn.bob.basic.utils;


import cn.bob.product.domain.Product;
import cn.bob.product.service.impl.ProductServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;


import java.io.*;
import java.util.List;

/**
 * @author bob
 * @data 2022/10/30-17:24
 */
public class FreemarkerUtil {
   private static Configuration configuration;
   private  static ProductServiceImpl productService;
    static {
        //创建模板技术的核心配置对象
        ApplicationContext context = SpringUtil.getContext();
        FreeMarkerConfigurer freeMarkerConfigurer= context.getBean(FreeMarkerConfigurer.class);
        productService = context.getBean(ProductServiceImpl.class);
        configuration= freeMarkerConfigurer.getConfiguration();
    }
    public static void createFreemark(String path, List<Long> ids) throws IOException {
        Template template = configuration.getTemplate("product.ftl");
        //准备数据
        createhtml(path, ids, template);


    }
    //抽取的创建html 调用freemarker模板创建
    private static void createhtml(String path, List<Long> ids, Template template) {
        ids.forEach(id->{
            Product pro = productService.bydetail(id);
            //合并模板
            FileWriter fileWriter = null;
            try {
                //判断是否没有图片
                if (StringUtils.isNotBlank(pro.getResources())){
                    String[] split = pro.getResources().split(",");
                    pro.setPics(split);
                }
                //判断文件是否存在已存在不创建
                File file = new File(path + "\\" + pro.getId() + ".html");
                fileWriter = new FileWriter(file);
                if (file.isFile() && file.exists()){
                    template.process(pro, fileWriter);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static void delFreemark(String path, List<Long> ids){
        ids.forEach(id->{
            File file = new File(path+"/"+id+".html");
            if (file.isFile() && file.exists()){
            file.delete();
            }
        });
    }
}
